package com.pwser.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import com.pwser.filter.JWTAuthenticationFilter;
import com.pwser.filter.JWTLoginFilter;
import com.pwser.filter.MyDisableUrlSessionFilter;
import com.pwser.handler.MyAccessDeniedHandler;
import com.pwser.service.LoginService;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private LoginService loginService;

//	@Autowired
//	private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

	@Autowired
	private MyAccessDeniedHandler myAccessDeniedHandler;

	// 不需要过滤的路径
	private static final String[] exclusivePaths = { "/", "/login", "/webjars/**", "/css/**", "/js/**", "/fonts/**",
			"/favicon.ico" };

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers(exclusivePaths).permitAll().anyRequest().authenticated();
		http.formLogin().loginPage("/login");
		http.addFilterBefore(new MyDisableUrlSessionFilter(), UsernamePasswordAuthenticationFilter.class);
		http.addFilterBefore(new JWTLoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
		http.addFilterAfter(new JWTAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
		//http.addFilterAfter(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
		http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
		http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
	}

	// 定义认证规则
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("zhangsan").password("123456").roles("VIP1","VIP2")
//                .and()
//                .withUser("lisi").password("123456").roles("VIP2","VIP3")
//                .and()
//                .withUser("wangwu").password("123456").roles("VIP1","VIP3");
		auth.userDetailsService(loginService).passwordEncoder(new BCryptPasswordEncoder());

	}
}
